<script lang="ts" setup>
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { toNumber } from 'lodash-es'
import { DeleteIcon, GetData, PatchModifyType, patchListSort } from '@/api/modules/vipIcon'

const imgDomain = 'https://img1.eprhan.cc'
const router = useRouter()

const findFrom = ref({
  Titile: '',
  LinkUrl: '',
})
const dataList: any = reactive({
  list: [],
  option: [],
})
const loading = ref(true)
const total = ref(0)
let PageSize = 20
let PageNum = toNumber(localStorage.getItem('currentPage')) || 1

const orderStatus = ref('')

// 导航栏切换时的回调
function handleSelect(key: string) {
  orderStatus.value = key
  GetDataList(PageNum, PageSize)
}

async function GetDataList(PageIndex: number = 1, PageSize: number = 20) {
  const params = {
    PageIndex,
    PageSize,
    ...(findFrom.value.Titile !== '' && ({ Titile: findFrom.value.Titile })),
    ...(findFrom.value.LinkUrl && ({ LinkUrl: findFrom.value.LinkUrl })),
    ...(orderStatus.value !== '' && ({ IconType: orderStatus.value })),
  }
  await GetData(params).then(async (dataRes: any) => {
    if (dataRes.succeeded) {
      dataList.list = dataRes.data.items
      total.value = dataRes.data.total
      loading.value = false
    }
  })
  loading.value = false
}
// 查询
function Inquire() {
  GetDataList(1, PageSize)
}

// 添加
function AddData() {
  router.push({
    name: 'vipIconDetail',
  })
}

// 编辑
function EditData(id: number) {
  localStorage.setItem('currentPage', `${PageNum}`)
  router.push({
    name: 'vipIconDetail',
    query: {
      id,
    },
  })
}

function SortModification(message: any) {
  const params = {
    id: message.row.id,
    sort: message.row.sort,
  }
  patchListSort(params).then((res: any) => {
    if (res.data) {
      ElMessage.success('修改成功。')
    }
    else {
      ElMessage.error('修改失败。')
      GetDataList()
    }
  })
}

// 删除
function Delete(id: number) {
  ElMessageBox.confirm(
    '你确定要删除吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      DeleteIcon(id).then((res: any) => {
        if (res.data) {
          ElMessage.success('删除成功。')
          GetDataList()
        }
        else {
          ElMessage.error('删除失败。')
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

async function ModifyType(params: any) {
  await PatchModifyType(params).then((res: any) => {
    if (res.statusCode === 200) {
      ElMessage.success('修改成功')
      GetDataList(PageNum, PageSize)
    }
    else {
      ElMessage.error(`修改失败${res.errors}`)
    }
  })
}

// 翻页
function handleSizeChange(val: number) {
  GetDataList(1, val)
  PageSize = val
}
function handleCurrentChange(val: number) {
  GetDataList(val, PageSize)
  PageNum = val
}

const nowPageNum = computed(() => {
  return toNumber(localStorage.getItem('currentPage')) || 1
})

onMounted(() => {
  if (localStorage.getItem('currentPage') !== null) {
    GetDataList(toNumber(localStorage.getItem('currentPage')), 20)
    localStorage.removeItem('currentPage')
  }
  else {
    GetDataList()
  }
})
</script>

<template>
  <div>
    <el-menu :default-active="orderStatus" class="el-menu-demo" mode="horizontal" @select="handleSelect">
      <el-menu-item index="">
        全部
      </el-menu-item>
      <el-menu-item index="1">
        会员攻略
      </el-menu-item>
      <el-menu-item index="2">
        会员权益
      </el-menu-item>
    </el-menu>
    <PageMain>
      <SearchBar :show-toggle="false">
        <div class="header">
          <el-form label-positio="right" label-width="auto">
            <div class="from">
              <el-form-item label="标题(最多6个字)">
                <el-input v-model="findFrom.Titile" style="width: 300px;" maxlength="6" placeholder="请输入标题" @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="跳转链接">
                <el-input v-model="findFrom.LinkUrl" style="width: 300px;" placeholder="请输入跳转链接" @keyup.enter="Inquire" />
              </el-form-item>
            </div>
          </el-form>
          <div class="text-right">
            <el-button @click="Inquire">
              查询
            </el-button>
          </div>
        </div>
      </SearchBar>
      <ElDivider border-style="dashed" />
      <div class="mb-5 text-right">
        <el-button type="success" @click="AddData">
          添加
        </el-button>
      </div>
      <el-table v-loading="loading" :data="dataList.list" stripe style="width: 100%;" border>
        <el-table-column align="center" prop="id" label="ID" width="100" />
        <el-table-column align="center" label="图标" width="150">
          <template #default="scope">
            <el-avatar shape="square" :size="80" :src="imgDomain + scope.row.iconPic" />
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" prop="display" label="是否展示" width="120">
          <template #default="scope">
            <el-tag>
              {{ scope.row.display === 1 ? '展示'
                : scope.row.display === 0 ? '隐藏' : '未定义' }}
            </el-tag>
          </template>
        </el-table-column> -->
        <el-table-column header-align="center" prop="title" label="标题" width="350" />
        <el-table-column header-align="center" prop="linkUrl" label="跳转链接" width="400" />
        <el-table-column align="center" prop="sort" label="排序" width="160">
          <template #default="scope">
            <el-input v-model="scope.row.sort" style="width: 120px;">
              <template #append>
                <el-button type="primary" size="small" @click="SortModification(scope)">
                  修改
                </el-button>
              </template>
            </el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" label="是否启用" width="120">
          <template #default="scope">
            <el-switch
              v-model="scope.row.enable"
              @click="ModifyType({ id: scope.row.id, enable: scope.row.enable })"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" fixed="right" min-width="220">
          <template #default="scope">
            <el-button type="primary" @click="EditData(scope.row.id)">
              编辑
            </el-button>
            <el-button type="danger" @click="Delete(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="height: 10px;" />
      <el-pagination
        :default-page-size="20"
        :page-sizes="[5, 10, 20, 50, 100]"
        layout="total, sizes, ->, prev, pager, next, jumper"
        :total="total"
        :default-current-page="nowPageNum"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </PageMain>
  </div>
</template>

<style scoped>
.header {
  display: grid;
  grid-template-columns: 6fr 1fr;

  .from {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    grid-gap: 20px;

    .el-form-item {
      margin-bottom: 0;
    }
  }
}
</style>
